import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { usePublicHooks } from "@/views/system/hooks";
import {
  getCloudList,
  changeCloudStatus,
  addCloud,
  updateCloud
} from "@/api/cloud";

import { getAccount } from "@/utils/auth";

export function useCloud(treeRef: Ref) {
  const form = reactive({
    pid: null,
    cloudName: null,
    cloudBasePath: null,
    tenantId: null,
    cloudDesc: null,
    archiveStatus: null
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const curTenantId = getAccount().tenantId;
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type:"index",
      width:60
    },
    {
      label: "服务云ID",
      prop: "pid",
      hide: true
    },
    {
      label: "服务云名称",
      prop: "cloudName"
    },
    {
      label: "服务云地址",
      prop: "cloudBasePath"
    },
    {
      label: "备注",
      prop: "cloudDesc",
      minWidth: 160
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.archiveStatus}
          active-value={"active"}
          inactive-value={"archive"}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChangeStatus(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onChangeStatus({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.archiveStatus === "archive" ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.cloudName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        changeCloudStatus(row.pid, row.archiveStatus)
          .then(function (data) {
            message(`更新服务云状态成功`, {
              type: "success"
            });
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
          })
          .catch(function (err) {
            row.archiveStatus === "archive"
              ? (row.archiveStatus = "active")
              : (row.archiveStatus = "archive");
            message(`更新服务云状态失败：${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {
        row.archiveStatus === "archive"
          ? (row.archiveStatus = "active")
          : (row.archiveStatus = "archive");
      });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    // loading.value = true;
    pagination.currentPage = val;
    onRefash();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function removeEmptyValues(obj) {
    return Object.keys(obj).reduce((acc, key) => {
      if (obj[key] !== null && obj[key] !== undefined && obj[key] !== "") {
        acc[key] = obj[key];
      }
      return acc;
    }, {});
  }

  function mergedParams() {
    const data = {
      ...toRaw(form),
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    return removeEmptyValues(data);
  }

  async function onSearch() {
    loading.value = true;
    pagination.currentPage = 1;
    getCloudList(curTenantId, mergedParams())
      .then(function (data) {
        dataList.value = data.data.list;
        pagination.total = data.data.total;
        pagination.pageSize = data.data.pageSize;
        pagination.currentPage = data.data.currentPage;
        pagination.pageCount = data.data.totalPage;
      })
      .catch(function (err) {
        message(`获取服务云清单异常：${err.message}`, {
          type: "error"
        });
      });
    loading.value = false;
  }

  async function onRefash() {
    loading.value = true;
    getCloudList(curTenantId, mergedParams())
      .then(function (data) {
        dataList.value = data.data.list;
        pagination.total = data.data.total;
        pagination.pageSize = data.data.pageSize;
        pagination.currentPage = data.data.currentPage;
        pagination.pageCount = data.data.totalPage;
      })
      .catch(function (err) {
        message(`获取服务云清单异常：${err.message}`, {
          type: "error"
        });
      });
    loading.value = false;
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}服务云`,
      props: {
        formInline: {
          pid: row?.pid ?? "",
          cloudName: row?.cloudName ?? "",
          cloudBasePath: row?.cloudBasePath ?? "",
          tenantId: row?.tenantId ?? "",
          cloudDesc: row?.cloudDesc ?? "",
          archiveStatus: row?.archiveStatus ?? "active",
          editStatus: title == "新增" ? false : true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        curData.tenantId = getAccount().tenantId;
        function chores() {
          message(`保存${curData.cloudName}信息成功`, {
            type: "success"
          });
          done(); // 关闭弹框
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              addCloud(curData)
                .then(function (data) {
                  chores();
                  onSearch();
                })
                .catch(function (err) {
                  message(`保存${curData.cloudName}信息异常：${err.message}`, {
                    type: "error"
                  });
                });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              updateCloud(curData, curData.pid)
                .then(function (data) {
                  chores();
                  onRefash();
                })
                .catch(function (err) {
                  message(`保存${curData.cloudName}信息异常：${err.message}`, {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { pid } = row;
    if (pid) {
      curRow.value = row;
      isShow.value = true;
      // const { data } = await getRoleMenuIds({ id });
      // treeRef.value.setCheckedKeys(data);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { pid } }) {
    return {
      cursor: "pointer",
      background: pid === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { pid, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    console.log(pid, treeRef.value.getCheckedKeys());
    message(`账户名称为${name}的菜单权限修改成功`, {
      type: "success"
    });
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    // const { data } = await getRoleMenu();
    // treeIds.value = getKeyList(data, "id");
    // treeData.value = handleTree(data);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    onSearch,
    onRefash,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
